#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任务处理器统一接口
"""

from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any, Callable
from enum import Enum


class ProcessingStrategy(Enum):
    """处理策略"""
    SERIAL = "serial"  # 串行处理
    PARALLEL = "parallel"  # 并行处理
    BATCH = "batch"  # 批量处理
    ADAPTIVE = "adaptive"  # 自适应处理


class TaskStatus(Enum):
    """任务状态"""
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"


@dataclass
class TaskItem:
    """任务项"""
    task_id: str
    task_type: str
    data: Dict[str, Any]
    priority: int = 0  # 优先级，数字越大优先级越高
    dependencies: List[str] = field(default_factory=list)  # 依赖的其他任务ID
    metadata: Dict = field(default_factory=dict)


@dataclass
class ProcessingResult:
    """处理结果"""
    total_tasks: int = 0
    completed_tasks: int = 0
    failed_tasks: int = 0
    cancelled_tasks: int = 0
    processing_time: float = 0.0
    results: Dict[str, Any] = field(default_factory=dict)
    errors: Dict[str, str] = field(default_factory=dict)  # task_id -> error_message
    metadata: Dict = field(default_factory=dict)

    @property
    def success_rate(self) -> float:
        """成功率"""
        if self.total_tasks == 0:
            return 0.0
        return self.completed_tasks / self.total_tasks

    @property
    def is_successful(self) -> bool:
        """是否全部成功"""
        return self.failed_tasks == 0 and self.cancelled_tasks == 0


class ITaskProcessor(ABC):
    """任务处理器统一接口"""

    @abstractmethod
    def process(self, tasks: List[TaskItem], strategy: ProcessingStrategy = ProcessingStrategy.ADAPTIVE) -> ProcessingResult:
        """
        处理任务列表

        Args:
            tasks: 任务列表
            strategy: 处理策略

        Returns:
            ProcessingResult: 处理结果
        """
        pass

    @abstractmethod
    def process_single(self, task: TaskItem) -> Dict[str, Any]:
        """
        处理单个任务

        Args:
            task: 任务项

        Returns:
            Dict: 处理结果
        """
        pass

    @abstractmethod
    def register_handler(self, task_type: str, handler: Callable[[TaskItem], Dict]):
        """
        注册任务处理器

        Args:
            task_type: 任务类型
            handler: 处理函数
        """
        pass

    @abstractmethod
    def set_max_workers(self, max_workers: int):
        """
        设置最大工作线程数

        Args:
            max_workers: 最大线程数
        """
        pass

    @abstractmethod
    def set_batch_size(self, min_size: int, max_size: int):
        """
        设置批处理大小

        Args:
            min_size: 最小批大小
            max_size: 最大批大小
        """
        pass

    @abstractmethod
    def cancel_task(self, task_id: str) -> bool:
        """
        取消任务

        Args:
            task_id: 任务ID

        Returns:
            bool: 是否成功取消
        """
        pass

    @abstractmethod
    def get_task_status(self, task_id: str) -> TaskStatus:
        """
        获取任务状态

        Args:
            task_id: 任务ID

        Returns:
            TaskStatus: 任务状态
        """
        pass

    @abstractmethod
    def get_statistics(self) -> Dict:
        """
        获取统计信息

        Returns:
            Dict: 统计信息
        """
        pass